$(function () {
    var initialLocaleCode = 'zh-cn';

    function getHolidayEvents(holidays, color) {
        var events = [];
        for (var key in holidays) {
            events.push(
                {
                    "color": color,
                    "start": key,
                    "manhour": 0,
                    "remark": '',
                    "title": '_' + holidays[key] + '_'
                }
            );
        }
        return events;
    }

    function pad(n, width, z) {
        z = z || '0';
        n = n + '';
        return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
    }

    function isHolidaysOffset(d) {
        var year = d.getFullYear();
        var month = d.getMonth() + 1;
        var date = d.getDate();
        var result = typeof (holidaysOffset[[year, pad(month, 2), pad(date, 2)].join('-')]) != 'undefined'
        return result;
    }

    function isNotHoliday(d) {
        var year = d.getFullYear();
        var month = d.getMonth() + 1;
        var date = d.getDate();
        var result = typeof (holidays[[year, pad(month, 2), pad(date, 2)].join('-')]) === 'undefined'
        return result;
    }

    function isHoliday(d) {
        var weekDay = d.getDay();
        if (weekDay != 0 && weekDay != 6 && isNotHoliday(d)) {
            return false;
        } else {
            if (isHolidaysOffset(d)) {
                return false;
            } else {
                return true;
            }
        }
    }

    function getWorkingDays(startDate, endDate) {
        var result = 0;
        var currentDate = startDate;
        while (currentDate < endDate) {
            var weekDay = currentDate.getDay();
            if (weekDay != 0 && weekDay != 6) {
                if (isNotHoliday(currentDate)) {
                    result++;
                }
            } else {
                if (isHolidaysOffset(currentDate)) {
                    result++;
                }
            }
            currentDate.setDate(currentDate.getDate() + 1);
        }
        return result;
    }


    // 配置fullCalendar
    $('#calendar').fullCalendar({
        header: {
            left: 'prev,today,next',
            center: 'title',
            right: 'basicWeek,basicDay,month,listMonth'
        },

        defaultView: 'listMonth',
        listDayAltFormat: false,
        firstDay: 1,

        locale: initialLocaleCode,

        showNonCurrentDates: false,
        buttonIcons: false,
        editable: false,
        draggable: false,
        weekNumbers: true,
        navLinks: false, // 禁止通过点击日期到日视图
        selectable: true,
        selectHelper: false,
        eventLimit: true, // allow "more" link when too many events

        eventTextColor: '#000000',


        // 显示每日事件
        // 异步获取月事件，自带起始日期
        eventSources: [
            // 假日
            {
                events: getHolidayEvents(holidays, "#1ef8ff")
            },
            // 补班
            {
                events: getHolidayEvents(holidaysOffset, "#4b97ff")
            },
            // 分配的任务
            // {
            //     url: 'ajaxs/assignments',
            //     error: function () {
            //         $('#script-warning').show();
            //     }
            // },
            // 正常工日
            {
                url: 'ajaxs/events',
                error: function () {
                    $('#script-warning').show();
                }
            }

        ],
        eventClick: function (info) {

            $('#jobnumber').val(info.jobnumber);
            $('#project').val(info.project);
            $('#manhour').val(info.manhour);
            $('#category').val(info.category);
            $('#subcategory').val(info.subcategory);
            $('#title').val(info.title);
            $('#remark').val(info.remark);

            $('#event-detail-modal').modal();
        },

        // 日程
        eventRender: function (event, element, view) {
            if (event.jobnumber != undefined) {
                $(element).find(".fc-list-item-title").prepend('<a>'
                    + '<span style="color: #27bd07">' + event.jobnumber + ' </span>'
                    + '<span style="color: #0058ff">' + event.project + ' </span>'
                    + '<br><span style="color: #0058ff">' + event.manhour + 'h </span>'
                    + '</a>').append('<br><a style="color: #db5c3e">' + event.remark + '</a>');
            }
        },

        // 显示每日工时总和
        eventAfterAllRender: function (view) {
            var start = view.start.format('YYYY-MM-DD');
            var end = view.end.format('YYYY-MM-DD');
            var overwork = 0;
            var normwork = 0;
            $('#manhourSummary').empty();
            $.ajax({
                url: 'ajaxs/count?start=' + start + '&end=' + end,
                success: function (data) {
                    for (cDay = view.start.clone(); cDay.isBefore(view.end); cDay.add(1, 'day')) {
                        var dateNum = cDay.format('YYYY-MM-DD');
                        var dayEl = $('.fc-day[data-date="' + dateNum + '"]');
                        var d = new Date(dateNum);

                        var countText = '';

                        var count = data['task'][dateNum];
                        if (count == null) {
                            count = '0';
                            countText = '0';
                        };


                        var color = 'White';
                        var i = parseFloat(count);
                        if (i <= 0) {
                            color = 'White';
                            countText = '0';
                        } else if (i <= 8) {
                            color = 'Green'
                            countText = count.toString();
                            if (isHoliday(d)) {
                                overwork += i;
                            } else {
                                normwork += i;
                            }
                        } else {
                            color = 'Red';
                            countText = '8 + ' + (i - 8).toFixed(1).toString();
                            if (isHoliday(d)) {
                                overwork += i;
                            } else {
                                normwork += 8;
                                overwork = overwork + (i - 8);
                            }
                        }

                        var html = '<span class="event-count" style="color:' + color + '">' +
                            '<i>' +
                            countText +
                            '</i>' +
                            '</span>';

                        dayEl.empty();
                        dayEl.append(html);
                    }

                    // 需要处理的问题
                    // 1 周末假日加班与正常上班工时分离。
                    // 2 添加休假类型统计

                    if (normwork > 0) {
                        $('#manhourSummary').append('<span class="label label-success">上班:' + normwork.toString() + '小时;</span>');
                    }

                    if (overwork > 0) {
                        $('#manhourSummary').append('<span class="label label-danger">加班:' + overwork.toString() + '小时;</span>');
                    }

                    for (var key in data['vacation']) {
                        $('#manhourSummary').append('<span class="label label-default">' + key + ':' + data['vacation'][key] + '小时;</span>');

                    }
                }
            });

            var begin = new Date(start);
            var end = new Date(end);
            var workingDays = getWorkingDays(begin, end)
            $('#manhourSummary').append('<span class="label label-primary">标准:' + workingDays * 8 + '小时(' + workingDays + '天);</span>');

        }
    });
});
